package study.thread.basic;

/*
 * 线程调用Thread.interrupted()判断是否接收到中断请求，如果接收到则返回true
 */
public class InterruptedTest2 extends Thread {
	static int count = 0;
	
	
	public InterruptedTest2(String name) {
		super(name);
	}
	
	public void run() {
		System.out.println(this.getName()+" 开始计算");

		for (int i = 0; i < 200008; i++) {
			count++;
			
			if (Thread.interrupted()) {
				System.out.println(this.getName()+" 被中断！循环结束！");
				
				//在更加复杂的应用程序里，线程收到中断异常后抛出InterruptedException可能更有意义
				try {
					throw new InterruptedException();
				} catch (InterruptedException e) {
					System.out.println(" throw InterruptedException！");
					//e.printStackTrace();
				}
				
				return;//返回
			}
		}
		
		System.out.println(this.getName()+" 结束计算==> "+count);
	}

	public static void main(String[] args) {
		System.out.println("==========《主线程执行》==========");
		Thread thread = new InterruptedTest2("计算线程");
		
		thread.start();
		
		System.out.println("count=====> "+count);
		try {
			long start = System.currentTimeMillis();
			//主线程暂停10ms
			thread.join(10);
			
			//主线程向计算线程发中断请求
			thread.interrupt();
			
			long end = System.currentTimeMillis();
			
			System.out.println(end-start+" ms 后 count = "+count);
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

}
